<?php

namespace app\services\activity;

use app\dao\activity\ActivityCategoryDao;
use app\services\BaseServices;
use crmeb\exceptions\AdminException;

class ActivityCategoryService extends BaseServices
{

    public function __construct(ActivityCategoryDao $dao)
    {
        $this->dao = $dao;
    }


    public function getList()
    {
        $list = $this->dao->getList();
        $list = get_tree_children($list);
        $count = $this->dao->count();
        return compact('list', 'count');
    }

    public function save($id, $params)
    {
        if (!isset($params['cate_name']) || !$params['cate_name']) throw new AdminException(400100);

        if ($id) {
            $this->dao->update($id, ['cate_name' => $params['cate_name'], 'parent_id' => $params['parent_id'] ?? 0 ]);
        } else {

            $pid = isset($params['pid']) ? $params['pid'] : 0;
            if ($pid && $this->dao->count(['id' => $pid]) == 0) throw new AdminException(400745);


            $this->dao->save([
                'cate_name'  =>  $params['cate_name'],
                'pid' =>  $params['pid'] ?? 0,
                'add_time'  =>  time()
            ]);
        }
        return true;
    }


    public function setShow($ids, $status)
    {
        $this->dao->batchUpdate($ids, ['status' => $status]);
        return true;
    }

    public function delete($id)
    {
        $res = $this->dao->update($id, ['is_del' => 1]);
        if (!$res) throw new AdminException(100008);
    }
}